package com.zx.mes.hyl.listener;

import com.netflix.discovery.shared.Applications;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import org.apache.log4j.Logger;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRegisteredEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaRegistryAvailableEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * Eureka 各种事件监听
 * EurekaInstanceCanceledEvent：失效事件
 * EurekaInstanceRegisteredEvent：注册事件
 * EurekaInstanceRenewedEvent：心跳事件
 * EurekaRegistryAvailableEvent：可用事件
 * EurekaServerStartedEvent：启动事件
 * @author hyl
 * @date 20178-1-8
 */
@Configuration
@EnableScheduling
public class EurekaInstanceListener implements ApplicationListener{

    private static final Logger logger=Logger.getLogger(EurekaInstanceListener.class);

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        //服务挂掉自动通知
        if (event instanceof EurekaInstanceCanceledEvent){
            EurekaInstanceCanceledEvent canceledEvent= (EurekaInstanceCanceledEvent) event;
            //获取当前Eureka实例中的节点信息
            PeerAwareInstanceRegistry registry= EurekaServerContextHolder.getInstance().getServerContext().getRegistry();
            Applications applications=registry.getApplications();
            //遍历获取已注册 节点中与当前失效节点ID一致的节点信息
            applications.getRegisteredApplications().forEach((registerApplication)->{
                registerApplication.getInstances().forEach((instance)->{
                    if (instance.getInstanceId().equals(canceledEvent.getServerId())){
                        logger.info("服务:"+instance.getAppName()+"挂掉了..." +" IP: " +instance.getIPAddr());
                    }
                });
            });
        }

        //服务注册信息
        if (event instanceof EurekaInstanceRegisteredEvent){
            EurekaInstanceRegisteredEvent registeredEvent= (EurekaInstanceRegisteredEvent) event;
            logger.info("服务: "+registeredEvent.getInstanceInfo().getAppName()+" 注册成功了!");
        }
        //服务可用事件
        if (event instanceof EurekaRegistryAvailableEvent){
            logger.info("服务 Available");
        }
    }
}
